package com.hhh.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhh.Mapper.ShoppingCartMapper;
import com.hhh.Pojo.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShoppingCartSerivce implements com.hhh.Service.ShoppingCartSerivce {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    //    往购物车里添加菜品
    @Override
    @Transactional
    public Integer Insert(ShoppingCart shoppingCart) {
//        查询购物车里有没有该用户相同的菜品
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", shoppingCart.getUserId()).
                eq("dish_id", shoppingCart.getDishId());
        ShoppingCart selectOne = shoppingCartMapper.selectOne(wrapper);
        if (selectOne != null) {
//            有则修改数据
            selectOne.setNumber(selectOne.getNumber() + 1);
            return shoppingCartMapper.updateById(selectOne);
        } else
//            没有则插入
            return shoppingCartMapper.insert(shoppingCart);
    }


    //    查询购物车
    @Override
    public List<ShoppingCart> SelectList(ShoppingCart shoppingCart) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", shoppingCart.getUserId());
        return shoppingCartMapper.selectList(wrapper);
    }

    //    从购物车里清除菜品
    @Override
    @Transactional
    public Integer Drop(ShoppingCart shoppingCart) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", shoppingCart.getUserId()).
                eq("dish_id", shoppingCart.getDishId());
        ShoppingCart selectOne = shoppingCartMapper.selectOne(wrapper);
        if (selectOne.getNumber() <= 1) {
            return shoppingCartMapper.deleteById(selectOne.getId());
        } else {
            selectOne.setNumber(selectOne.getNumber() - 1);
            return shoppingCartMapper.updateById(selectOne);
        }
    }

    @Override
    public Integer Delete(long id) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        return shoppingCartMapper.delete(wrapper);
    }
}
